package org.hscoder.mongo.sync;

import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.management.JMXConnectionPoolListener;

import java.util.ArrayList;
import java.util.List;

public class MongoClientFactory {

    public static MongoClient build() {
        //服务器实例表
        List<ServerAddress> servers = new ArrayList<>();
        servers.add(new ServerAddress("47.106.80.151", 27018));

        String username = "admin";
        String password = "admin@2016";
        String database = "admin";

        //初始化凭证
        MongoCredential credential = MongoCredential.createCredential(username, database, password.toCharArray());

        //配置构建器
        MongoClientSettings.Builder settingsBuilder = MongoClientSettings.builder();

        //传入服务器实例
        settingsBuilder.applyToClusterSettings(
                builder -> builder.hosts(servers));

        settingsBuilder.credential(credential);

        //添加JMX 监听
        settingsBuilder.applyToConnectionPoolSettings( builder -> {
            builder.addConnectionPoolListener(new JMXConnectionPoolListener());
        });

        //构建 Client 实例
        MongoClient mongoClient = MongoClients.create(settingsBuilder.build());
        return mongoClient;
    }
}
